<template>
  <div>
    <div class="box-border p-12px">
      <el-form ref="formRef" :rules="rules" :model="form" class="mt-12px">
        <div class="mt-16px">
          <SubTitle title="文件导入" />
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="form.deptId"
              clearable
              placeholder="请选择归属机构"
              :options="options"
              :props="cascaderProps"
              filterable
              value-on-clear=""
            />
          </el-form-item>
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="form.sysId"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              value-on-clear=""
              clearable
          /></el-form-item>
          <el-form-item label="批次号码" prop="batchNum" v-if="route.name == 'ExitFile'">
            <el-input-number v-model="form.batchNum" />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <Icon icon="svg-icon:tips" />
            <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
          </el-form-item>
          <el-form-item label="数据保护标准" prop="template">
            <el-select v-model="form.template" clearable placeholder="请选择数据标准">
              <el-option
                v-for="(template, templateIndex) in templateList"
                :key="templateIndex"
                :label="template.dataStandardName"
                :value="template.id"
              /> </el-select
          ></el-form-item>
          <el-form-item class="col-item" label="选择文件" prop="filePath">
            <el-upload
              class="w-90%"
              drag
              multiple
              v-model:file-list="form.filePath"
              :action="actionUrl"
              :headers="uploadHeaders"
              :before-upload="beforeUpload"
              :on-remove="uploadRemove"
              :on-success="uploadSuccess"
              :on-error="uploadError"
            >
              <!-- v-model:file-list="fileList" -->
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text"> 将文件拖至此处，或<em>点击选择</em> </div>
              <p>支持文件类型： {{ fileSuffix.join('、') }}</p>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="nextStep" :disabled="loading">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import SubTitle from '@/components/SubTitle/index.vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { handleTree } from '@/utils/tree'
import { assetUploadFile, assetExecClassification } from '@/api/assetList'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { fileSuffix } from '@/utils/uploadTypes'

const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const formRef = ref()
const loading = ref(false)
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})

const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}

const scanModeDetail = ref({
  type: '1'
})

const fileList = ref<any[]>([])
const actionUrl: string = import.meta.env.VITE_UPLOAD_URL
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})
const beforeUpload = (file: any) => {
  console.log(file)
  if (!fileSuffix.includes(file.name.split('.')[file.name.split('.').length - 1])) {
    message.error('文件类型不支持！')
    return false
  }
  return true
}
// 上传成功提示
const uploadSuccess = (res: any): void => {
  if (res.code === 1001003003) {
    uploadError(res)
    form.value.filePath.pop()
    return
  } else {
    formRef.value.validateField('filePath')
    let { data } = res
    fileList.value.push(data)
    console.log('fileList.value', fileList.value)
    proxy.$message.success('上传成功')
  }
}
//上传失败提示
const uploadError = (res: any): void => {
  proxy.$message.error(res.message)
}
const uploadRemove = (res: any): void => {
  let { response } = res
  let index = fileList.value.findIndex((item) => item.id == response.data.id)
  fileList.value.splice(index, 1)
}

const form = ref({
  deptId: '',
  sysId: '',
  template: null,
  batchNum: null,
  filePath: []
})

const isRequired = computed(() => {
  return !form.value.deptId && !form.value.sysId
})
const rules = computed(() => ({
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  batchNum: [{ required: true, message: '批次号码不能为空', trigger: 'change' }],
  template: [{ required: true, message: '数据保护标准不能为空', trigger: 'change' }],
  filePath: [{ required: true, message: '必须上传文件', trigger: 'blur' }]
}))

const nextStep = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      const data = await assetUploadFile({
        deptId: form.value.deptId == '' ? '0' : form.value.deptId,
        sysId: form.value.sysId,
        fileList: fileList.value,
        batchNum: form.value.batchNum,
        submitStatus: props.params.submitStatus || ''
      })
      if (data) {
        const formData = {
          ids: data.map((item) => item.id),
          template: form.value.template,
          objectType: 3
        }
        const res = await assetExecClassification(formData)
        if (res) {
          message.success('操作成功')
          props.params.callBack()
          props.closeOutDrawer()
        }
      }
      loading.value = true
    }
  })
}

const systemList = ref()
const options = ref()
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, type: 0, status: '1' })
  console.log('data', data)
  templateList.value = data
}
onMounted(() => {
  getSystemList()
  getDeptList()
  getTemplateList()
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
